<?php 
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: caijx <2877907559@qq.com>
// +----------------------------------------------------------------------
// | date:2017-12-04
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
class Common extends Controller
{
    protected function initialize()
    {
        parent::initialize();//继承父类中的初始化操作
        define('user_id',Session::get('user_id'));
        $this->isLogin();
    }
    //判断用户是否登录，放在后台的入口：index/index
    protected function isLogin()
    {
        $user_id = Session::get('user_id');
        if(empty($user_id)){
            $this -> error('请登录','index/index');
        }
    }

    /**
     * 防止用户重复登录
     */
    protected function alreadyLogin()
    {
        $user_id = Session::get('user_id');
        if(!empty($user_id))
        {
            $this->error('请勿重复登录',url('Index/index'));
        }
    }
    /**
     * 获取登录信息
     * @return unknown
     */
    public function getData() {
        $data ["user_id"] = Session::get('user_id');
        $data ["user_name"] = Session::get('user_name');
        $data ["user_type"] = Session::get('user_type');
        if(empty($data['user_id'])){
            $this->isLogin();
        }
        return $data;
    }
		/**
		 * 退出系统
		 */
    public function logout(){
        //更新登录表的退出时间
        Db::name('login')->where('user_id',Session::get('user_id'))
            ->update(['exit_time'=>time()]);
        //删除用户登录信息用：session
        Session::delete('user_id');//用户id
        Session::delete('user_name');//用户名
        Session::delete('user_type');//用户类型
        Session::delete('login_id'); //登录id
        $this->redirect('Index/index');
    }
		/**
		 * 查询学段（小初高）
		 */
	    public function get_school(){
	        $school_list = Db::query('select id,name from tp_school');
	        $this->view->assign('school_list', $school_list);
	    }
	    /**
	     * 获取学科
	     * @param unknown $school
	     * @return number[]|unknown[]|NULL[]|number[]
	     */
	    public function get_subject($school) {
	        $list = Db::query('select id,name from tp_subject where status=1 and isdelete=0 and school='.$school);
	        if(!empty($list)) {
	            //$this->ajaxReturn($data, "查询成功", 1);
	            return  ['data'=>$list,'status'=>1];
	        } else {
	            return  ['data'=>null,'status'=>0];
	        }
	    }
	    /**
	     * 获取年级
	     * @param unknown $school
	     * @return number[]|unknown[]|NULL[]|number[]
	     */
	    public function get_class($school) {
	        //$province_code = $this->request->post('province_code');
	        $list = Db::query('select id,name from tp_classes where status=1 and isdelete=0 and school='.$school);
	        if(!empty($list)) {
	            //$this->ajaxReturn($data, "查询成功", 1);
	            return  ['data'=>$list,'status'=>1];
	        } else {
	            return  ['data'=>null,'status'=>0];
	        }
	    }
	    /**
	     * 获取省份
	     * @return unknown
	     */
	    public function get_province_list(){
	        $list = Db::query('select code,name from tp_province');
	        //$list = $model->select();
	        return $list;
	    }
	    public function get_city_list(){
	        $list = $list = Db::query('select code,name from tp_city');
	        return $list;
	    }
	    public function get_area_list(){
	        $list = $list = Db::query('select code,name from tp_area');
	        return $list;
	    }
	   /**
	    * 获取市州
	    * @param unknown $province_code
	    * @return number[]|unknown[]|NULL[]|number[]
	    */
	    public function get_city_code($province_code) {
	        //$province_code = $this->request->post('province_code');
            $list = Db::name('city')->where('province_code',$province_code)->field(['code','name'])->select();
	        if(!empty($list)) {
	            //$this->ajaxReturn($data, "查询成功", 1);
	            return  ['data'=>$list,'status'=>1];
	        } else {
	            return  ['data'=>null,'status'=>0];
	        }
	    }
	    /**
	     * 获取县区
	     * @param unknown $city_code
	     * @return number[]|unknown[]|NULL[]|number[]
	     */
	    public function get_area_code($city_code){
	        $list = Db::query('select code,name from tp_area where city_code=:city_code',['city_code'=>$city_code]);
	        if(!empty($list)) {
	            //$this->ajaxReturn($data, "查询成功", 1);
	            return  ['data'=>$list,'status'=>1];
	        } else {
	            return  ['data'=>null,'status'=>0];
	        }
	    }

        /**
         * 文件大小转换
         * @param $size
         * @return string
         */
        protected function getSuitSize($size)
        {
            $unit = ['B','KB','MB','GB','TB'];
            $i = 0;
            while ($size >= 1024) {
                $size /= 1024;
                $i++;
            }
            //如果有小数点
            if (is_float($size)) {
                $size = number_format($size,1);
            }

            return $size.$unit[$i];
        }
	    /**
	     * 获取时间
	     * @return unknown
	     */
	    public function get_date() {
	        $date = date('Y-m-d H:i:s');
	        return $date;
	    }
	    /**
	     * 删除文件
	     * @param unknown $path
	     * @return boolean
	     */
	    public function unlink($path)
	    {
	    	return is_file($path) && unlink($path);
	    }
	    /**
	     * 获取子级评论
	     * @return number[]|unknown[]|NULL[]|number[]
	     */
	    public function get_parent_com() {
	        $sql="SELECT CASE WHEN b.user_type='a' THEN get_teacher_name(b.user_id) WHEN b.user_type='b' THEN get_student_name(b.user_id) END AS  user_name,mark,time,ParentCommentId,CaseId,Comment,a.id  FROM tp_comment a LEFT JOIN tp_user_base b ON a.user_base_id=b.id WHERE a.CaseId='".$id."'and a.status='1' and a.ParentCommentId IS NULL";
	        $comment=Db::query($sql);
	        if(!empty($list)) {
	            //$this->ajaxReturn($data, "查询成功", 1);
	            return  ['data'=>$list,'status'=>1];
	        } else {
	            return  ['data'=>null,'status'=>0];
	        }
	    }
	    /**
	     * 获取子级评论
	     * @return number[]|unknown[]|NULL[]|number[]
	     */
	    public function get_child_com() {
	       $comid=$this->request->post('comid');
	      // $list = Db::query('select * from tp_comment where ParentCommentId ="'.$comid.'"');
	       $sql="SELECT *,get_commentor(user_base_id) AS user_name FROM tp_comment WHERE ParentCommentId='".$comid."'and status='1'";
	       $list=Db::query($sql);
	        if(!empty($list)) {
	            //$this->ajaxReturn($data, "查询成功", 1);
	            return  ['data'=>$list,'status'=>1];
	        } else {
	            return  ['data'=>null,'status'=>0];
	        }
	    }

        /**
         * 删除指定地址下的文件
         * @param $path 文件路径
         * @return bool
         */
	    public function delFile($path) {
	    	try {
	    		if(file_exists($path)) {
	    			return is_file($path) && unlink($path);
	    		}
	    	} catch (Exception $e) {
	    		echo $e->getMessage();
	    	}
	    }
    /**
     * 处理文件
     * @param $file resource
     * @param $size array
     * @param $format array
     * @param $folder string
     * @return mixed
     */
    public static function doFileData($file,$size,$format,$folder)
    {
        $info = $file->validate(['size'=>$size,'ext'=>$format])->move(ROOT_PATH.'public'.DS.'uploads\\'.$folder);
        if ($info) {
            $file_info['src'] = $info->getSaveName();
            $file_info['format'] = $info->getExtension();
            $file_info['size'] = $info->getSize();
            return $file_info;
        } else{
            return $file->getError();
        }
    }
    
    /**
     * 记录用户行为
     * @param string $type         操作类型
     * @param string $object_type  操作对象
     * @param $object_id    对象id
     * @return int|string 是否成功标识符
     */
    public function addRecord($type = '',$object_type = '',$object_id)
    {
        //当前请求控制器
        $model = request()->module();
        $controller = request()->controller();
        $action = request()->action();
        $action = $model.DS.$controller.DS.$action;
        //请求参数
        $param = request()->param();
        $param = is_array($param) ? implode(',',$param) : $param;
        //截取部分参数 防止太长数据库报错
        $param = count($param) > 50 ? substr($param,0,50) : $param;
        $data = [
            'login_id'              => Session::get('login_id'),
            'user_id'               => Session::get('user_id'),
            'user_type'             => Session::get('user_type'),
            'operation_type'        => $type,
            'operation_object_type' => $object_type,
            'object_id'             => $object_id,
            'operator'              => Session::get('user_id'),
            'action'                => $action,
            'param'                 => $param,
            'create_time'           => time(),
            'update_time'           => time(),
        ];
        return Db::name('base_operation')->insert($data);
    }

    /**
     * @return int|string 最后一次插入ID
     */
    public function addLoginInfo()
    {
        $request = Request::instance();
        $login_info = [
            'user_id'       => Session::get('user_id'),
            'login_time'    => time(),
            'login_device'  => \Agent::getOs(),
            'operator'      => Session::get('user_name'),
            'update_time'   => time(),
            'login_ip'      => $request->ip()
        ];
        Db::name('login')->insert($login_info);
        return Db::name('login')->getLastInsID();
    }
    /**
     * 根据时间戳获取日期中的月、天、时
     * @param $data 数据库中的数组
     * @param $format
     * @return mixed
     */
    public function getSuitData($data,$format='m')
    {
        foreach ($data as &$item) {
            $item['begin_time'] = date($format,$item['begin_time']);
        }
        return $data;
    }

    /**
     * 过滤敏感词
     * @param $string
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setKeyWord($string)
    {
        if (is_array($string)) {
            $string = implode(',',$string);
        }
        $list = Db::name('sensitive')->field(['word','replace'])->select();
        foreach ($list as $item) {
            $string = str_replace($item['word'],$item['replace'],$string);
        }
        return $string;
    }

    /**
     * 是否是微信内置浏览器
     * @return bool
     */
    public function isWeChatBrowser()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 是否手机端
     * @return bool
     */
    public function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
            return true;

        //此条摘自TPM智能切换模板引擎，适合TPM开发
        if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
            return true;
        //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
            //找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
        //判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array(
                'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
            );
            //从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        //协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }
    /**
     * http 请求
     * @param $url
     * @param null $data
     * @return mixed
     */
    protected function http_curl($url,$data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 获取视频路径
     * @param $id
     * @return bool|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function getPath($id)
    {
        $case_info = Db::name('cases')->where('id',$id)->field(['school','subject'])->find();
        $path = Db::name('subject')
            ->where(['school'=>$case_info['school'],'name'=>$case_info['subject']])
            ->value('path');
        if ($path) {
            return $path;
        } else {
            return null;
        }
    }
}